﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace OperaThumbnailer
{
	public partial class MainForm : Form
	{
		private OperaInstallsData installs;
		private SpeedDialData data;
		private Image oldThumb;
		private Image newThumb;
		
		public MainForm()
		{
			InitializeComponent();
		}
		
		void MainFormLoad(object sender, EventArgs e)
		{
			installs = new OperaInstallsData();
			cbThumbDir.DataSource = installs.Installations;
			fileDiag.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
			
			if (Process.GetProcessesByName("opera").Length > 0) {
				statusText.ForeColor = Color.Red;
				statusText.Text = "Opera is currently running. Changes made will not take effect until Opera is restarted.";
			}
			
			statusTimer.Enabled = true;
		}
		
		void CbThumbDirSelectedValueChanged(object sender, EventArgs e)
		{
			this.tipInfo.SetToolTip(
				this.pbxInfo,
				"Install Path: " + ((OperaInstallation)cbThumbDir.SelectedItem).InstallPath + "\n" +
				"Thumbnails Path: " + ((OperaInstallation)cbThumbDir.SelectedItem).ThumbnailDir + "\n" +
				"opthumb.dat Path: " + ((OperaInstallation)cbThumbDir.SelectedItem).ThumbDatPath + "\n"
			);
			RefreshThumbnailList();
		}
		
		void BtnRefreshClick(object sender, EventArgs e)
		{
			RefreshThumbnailList();
		}
		
		void RefreshThumbnailList()
		{
			btnReplace.Enabled = false;
			btnRefresh.Enabled = false;
			btnNewBrowse.Enabled = false;
			lbThumbList.Enabled = false;
			lbThumbList.DataSource = null;
			pbOldThumb.Image = (Image)null;
			pbNewThumb.Image = (Image)null;
			if (oldThumb != null) oldThumb.Dispose();
			if (newThumb != null) newThumb.Dispose();
			txtNewTitle.Enabled = false;
			txtNewTitle.ForeColor = SystemColors.GrayText;
			txtNewTitle.Text = "";
			
			if (data != null) data = null;
			data = new SpeedDialData(cbThumbDir.SelectedValue.ToString());
			btnRefresh.Enabled = true;
			lbThumbList.DataSource = data.Dials;
			lbThumbList.DisplayMember = "Title";
			lbThumbList.ValueMember = "ThumbFile";
			lbThumbList.SelectedIndex = -1;
			lbThumbList.Enabled = true;
		}
		
		void LbThumbListSelectedValueChanged(object sender, EventArgs e)
		{
			pbNewThumb.Image = (Image)null;
			if (newThumb != null) newThumb.Dispose();
			LoadSelectedThumbnail();
		}
		
		void LoadSelectedThumbnail()
		{
			if (!lbThumbList.Enabled || lbThumbList.SelectedIndex < 0) return;
			if (oldThumb != null) oldThumb.Dispose();
			
			FileInfo thumbFile = new FileInfo(((OperaInstallation)cbThumbDir.SelectedItem).ThumbnailDir + @"\" + lbThumbList.SelectedValue.ToString());
			thumbFile.IsReadOnly = false;
			
			FileStream fs = new FileStream(thumbFile.FullName, FileMode.Open);
			oldThumb = Image.FromStream(fs);
			fs.Close();
			fs.Dispose();
			
			thumbFile.IsReadOnly = true;
			
			pbOldThumb.Image = oldThumb;
			btnNewBrowse.Enabled = true;
			
			txtNewTitle.Enabled = true;
			txtNewTitle.Text = "Click here to set new title";
			txtNewTitle.ForeColor = SystemColors.GrayText;
			
			btnReplace.Enabled = true;
		}
		
		void BtnNewBrowseClick(object sender, EventArgs e)
		{
			fileDiag.Dispose();
			fileDiag = new OpenFileDialog();
			fileDiag.Title = "Select Image or Input URL";
			fileDiag.RestoreDirectory = true;
			if (fileDiag.ShowDialog(this) == DialogResult.OK) {
				try {
					if (newThumb != null) newThumb.Dispose();
					newThumb = Image.FromFile(fileDiag.FileName);
					pbNewThumb.Image = newThumb;
					btnReplace.Enabled = true;
				} catch (Exception) {
					MessageBox.Show("Error loading image. Possibly not an image to begin with.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
			}
		}
		
		void BtnReplaceClick(object sender, EventArgs e)
		{
			statusText.Text = "";
			statusText2.Text = "";
			if (pbNewThumb.Image != null) {
				FileInfo oldThumbFile = new FileInfo(((OperaInstallation)cbThumbDir.SelectedItem).ThumbnailDir + @"\" + lbThumbList.SelectedValue.ToString());
				oldThumbFile.IsReadOnly = false;
				
				statusTimer.Stop();
				
				try {
					pbOldThumb.Image = (Image)null;
					oldThumb.Dispose();
					pbNewThumb.Image.Save(oldThumbFile.FullName, System.Drawing.Imaging.ImageFormat.Png);
					statusText.ForeColor = Color.Green;
					statusText.Text = "Image saved successfully.";
				} catch (Exception) {
					statusText.ForeColor = Color.Red;
					statusText.Text = "Error saving image. (In use by other program.) ";
				}
				
				statusTimer.Start();
				
				oldThumbFile.IsReadOnly = true;
			}
			
			if (txtNewTitle.ForeColor == Color.Black && txtNewTitle.Text != "") {
				string opThumbPath = ((OperaInstallation)cbThumbDir.SelectedItem).ThumbDatPath;
				string opthumbText = File.ReadAllText(opThumbPath);
				string pattern = lbThumbList.SelectedValue.ToString() + "(...)" + ((Dial)lbThumbList.SelectedItem).Title;
				string replacement = lbThumbList.SelectedValue.ToString() + "$1" + txtNewTitle.Text;
				try {
					new FileInfo(opThumbPath).IsReadOnly = false;
					File.WriteAllText(opThumbPath, Regex.Replace(opthumbText, pattern, replacement));
					statusText2.ForeColor = Color.Green;
					statusText2.Text = "Title replacement successful.";
				} catch (Exception) {
					statusText2.ForeColor = Color.Red;
					statusText2.Text = "Title replacement failed. opthumb.dat in use.";
				}
			}
			
			int selected = lbThumbList.SelectedIndex;
			RefreshThumbnailList();
			lbThumbList.SelectedIndex = selected;
		}
		
		void StatusTimerTick(object sender, EventArgs e)
		{
			statusText2.Text = "";
			if (Process.GetProcessesByName("opera").Length > 0) {
				statusText.ForeColor = Color.Red;
				statusText.Text = "Opera is currently running. Changes made will not take effect until Opera is restarted.";
			} else {
				statusText.Text = "";
			}
		}
		
		void TxtNewTitleEnter(object sender, EventArgs e)
		{
			if (txtNewTitle.ForeColor == SystemColors.GrayText) {
				txtNewTitle.Text = "";
				txtNewTitle.ForeColor = Color.Black;
			}
		}
		
		void TxtNewTitleLeave(object sender, EventArgs e)
		{
			if (txtNewTitle.Text == "") {
				txtNewTitle.Text = "Click here to set new title";
				txtNewTitle.ForeColor = SystemColors.GrayText;
			}
		}
		
		void BtnHelpClick(object sender, EventArgs e)
		{
			string filePath = Path.GetTempPath() + @"\customizer_readme.txt";
			try { File.Delete(filePath);}
			catch (Exception) {}
			
			if (!File.Exists(filePath)) {
				try {
					File.WriteAllText(filePath, Resource.readme);
				} catch (Exception) {
					MessageBox.Show(Resource.readme);
					return;
				}
			}
			Process.Start(filePath);
		}
	}
}

